<template>
	<view class="apps">
		<view class=" mtb20 ptb10 plr10 bgwhite flex fdc" v-if="detail">
			<view class="flex fdc">
				<view class="tic">
					<image :src="detail.mobileImg || detail.pcImg "></image>
				</view>
				<view class="ptb20 f14 fweight4">{{detail.name}}</view>
				<view class="flex jcsb f12">
					<view class="c666 flex aic">
						<uv-icon name="clock" size="20"></uv-icon>
						<text>{{ timeFormat(detail.st) }}</text>
					</view>
					<view class="c888  flex aic" v-if="detail.city != ''">
						<uv-icon name="map" size="20"></uv-icon>
						<text>{{ detail.city}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="mtb20 ptb20 plr20 bgwhite felx  fdc" v-if="userAuth">
			<view class="flex ptb20 fweight6 black f30r">报名信息</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666">姓名:</view>
				<view class="f22r c999">{{payInfo.name}}</view>
			</view>
		</view>
		<view class="mtb20 ptb20 plr20 bgwhite felx  fdc" v-if="userAuth">
			<view class="flex ptb20 fweight6 black f30r">缴费信息</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666">参会身份:</view>
				<view class="f22r c999">{{ identityValue.name }}</view>
			</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666">会员</view>
				<view class="f22r c999">{{ memberStra.name}}</view>
			</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666"></view>
				<view class="f22r c999">{{ trainStra.name}}</view>
			</view>
		</view>
		<view class="mtb20 ptb20 plr20 bgwhite felx  fdc" v-if="!!useUserInfo().isLogin()">
			<view class="flex ptb20 fweight6 black f30r">用户信息</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666">手机号:</view>
				<view class="f22r c999">{{loginUser.mobile}}</view>
			</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s" v-if="loginUser.email">
				<view class="f22r c666">邮箱:</view>
				<view class="f22r c999">{{loginUser.email}}</view>
			</view>
			<view class="flex ptb10 fweight4 jcsb bdb1s">
				<view class="f22r c666">姓名:</view>
				<view class="f22r c999">{{loginUser.infos[0].name}}</view>
			</view>
		</view>
		<uv-tabbar :value="0" :border="false">
			<uv-tabbar-item customStyle="flex:1;display:flex;flex-direction: column;">
				<template v-slot:text>
					<view class=" flex f1 aic jcc" v-if="detail.payee =='2'">
						<view class="ptb20 w540 flex jcc bgred white f28 br10">您未选择支付宝支付相关缴费信息</view>
					</view>
					<view class=" flex f1 aic" v-else>
						<view :class="IsConferenceStatus?`ptb20 w540 flex jcc bggray  f28 br10`:`ptb20 w540 flex jcc bgblue white f28 br10`" v-if="UserIsConference == 0" @click="getMyConference">获取报名&信息</view>
						<view class="ptb20 w540 flex jcc bgred white f28 br10" v-if="UserIsConference == 2">已缴费</view>
						<view class="ptb20 w540 flex jcc bgred white f28 br10" v-if="UserIsConference == 1">退款中</view>
						<view class="ptb20 w540 flex jcc  f28 br10" v-if="UserIsConference == 4"></view>
						<view :class="IsConferenceStatus?`ptb20 w540 flex jcc bggray  f28 br10`:`ptb20 w540 flex jcc bgblue white f28 br10`" v-if="UserIsConference == 3" @click="aliPayment">支付宝支付{{payment.paymentFee}}元</view>
					</view>
				</template>
			</uv-tabbar-item>
		</uv-tabbar>
	</view>
</template>

<script setup>
	import { ref , reactive, nextTick,toRefs, watch, getCurrentInstance  } from 'vue';
	const { proxy } = getCurrentInstance();
	const { $onLaunched } = proxy;
	import { onLoad,onShow } from '@dcloudio/uni-app'
	import { getConferenceDetail, getidentity, getstrategy } from '@/common/conference/index.js'
	import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import { useUserInfo } from '@/stores/userInfo.js'
	import { myConference,paymentPrepaied,paymentPaied,sessionCode,paymentUpdate,paymentClose,orderQuery,paymentLog } from '@/common/user/index.js'
	const id = ref('')
	const payId = ref('');
	const payment = ref({});
	const payInfo = ref({});
	const detail = ref({})
	const UserIsConference = ref(0) //
	const IsConferenceStatus=ref(false)
	const userAuth=ref(false)
	const strategy = ref(null)
	const identity = ref(null)
	const loginUser = ref({})
	const identityValue = ref('')
	const memberStra = ref('')
	const trainStra=ref('')

	//详情
	if(!!useUserInfo().isLogin()){
		loginUser.value=JSON.parse(uni.getStorageSync('alisinceUser'));
		console.log(loginUser.value);
	}
	const getDetail = ()=>{
		getConferenceDetail(id.value).then((rlt)=>{
			detail.value = rlt.data;
		}).finally(()=>{
			uni.hideLoading()
		})
	}
	//获取缴费信息
	const getMyConference = ()=>{
		if(!!useUserInfo().isLogin()){
			loginUser.value = JSON.parse(uni.getStorageSync('alisinceUser'));
			uni.showLoading()
			myConference(id.value,useUserInfo().getAccountId()).then((res)=>{
				uni.hideLoading();
				console.log(res);
				if(res.data == null){
					uni.showToast({
						title:'您尚未报名',
						duration:3000
					})
					IsConferenceStatus.value = true
				}else if( res.data && res.data.payment){
					identityValue.value = identity.value.find( item => item.id ===res.data.payment.identityId )
					if(res.data.payment.memberStrategyId !== null){
						memberStra.value = res.data.payment.memberStrategyId && strategy.value.find( item => item.id===res.data.payment.memberStrategyId )
					}
					if(res.data.payment.trainStrategyId !== null){
						trainStra.value =  strategy.value.find( item => item.id===res.data.payment.trainStrategyId )
					}
					
					userAuth.value = true
					payId.value = res.data.id
					payInfo.value = res.data
					payment.value = res.data.payment;
					 if(res.data.payment.paymentType === '2'){
						 
						 if(res.data.payment.paymentStatus === '0' || res.data.payment.paymentStatus === '3'){

							 UserIsConference.value=3
						 }
						 if(res.data.payment.paymentStatus === '1' ){
							
							 uni.showToast({
							 	title:'已缴费',
							 	duration:3000
							 })
							 UserIsConference.value=2
						 }
						 if(res.data.payment.paymentStatus === '2' ){
						 							
								 uni.showToast({
									title:'订单正在退款',
									duration:3000
								 })
								 UserIsConference.value=1
						 }
						 if(res.data.payment.paymentStatus === '4' ){
							 payInfo.value.paymentStatus = '0'
							 console.log(payInfo);
							 UserIsConference.value=0
							 uni.showToast({
								title:'订单支付中，请稍后',
								duration:3000
							 })
							 
							 UserIsConference.value=0
						 }
					 }else{
						
						 uni.showToast({
						 	title:'您未选择支付宝支付，请前往网站或微信小程序设置相关缴费信息',
						 	duration:3000
						 })
						 IsConferenceStatus.value = true
					 }
				}else{
					
					uni.showToast({
						title:'您未选择支付宝支付，请前往网站或微信小程序设置相关缴费信息',
						duration:3000
					})
					IsConferenceStatus.value = true
				}
			})
		}else{
			uni.showToast({
				title:"报名认证,需要登录",
				duration:1000,
				complete:function(){
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
			})
		}
	}
	
	const prePayment =  async ()=>{
		return  await paymentPrepaied(id.value,payment.value.id)

	}
	const Paied =  async(fee,cid,userid,pid)=>{
		return await paymentPaied({ fee: fee, 
          conferenceId: cid,
          zfb_userId: userid,userId:pid})
	}
	const aliPayment = async ()=>{
		if(!useUserInfo().isLogin()){
			uni.showToast({
				title:"报名缴费,需要登录",
				duration:1000,
				complete:function(){
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}
			})
			return;
		}
		loginUser.value = JSON.parse(uni.getStorageSync('alisinceUser'));
		const {code,data} = await prePayment();
		console.log(payInfo.value)
		console.log(payment.value);
		if( data.paymentFee && data.paymentFee === payment.value.paymentFee){ //useUserInfo.
			const { code, data } = await Paied(parseFloat(payment.value.paymentFee)*100,id.value,useUserInfo().getOpenid(),payInfo.value.id);
			const miniOrder = data;
			if(code == 0){
				uni.requestPayment({
					provider:'alipay',
					orderInfo:data.miniPayRequest.tradeNO,
					success:(payResult)=>{
						if(payResult.resultCode =='9000' && payResult.errMsg=="requestPayment:ok"){
							setTimeout( async function(){
								const { code, data } = await orderQuery(payment.value.tradeId,id.value)
								console.log(data);
								if(data.status === 'TRADE_SUCCESS'){
									const uprs = await paymentUpdate({
											 ...payment.value,
											 tradeId:payment.value.tradeId,
											 paymentStatus:'1',
											 paymentFee:payment.vlue.paymentFee,
											 type: 'union',
										},payment.value.id);
									const uplog = await paymentLog({
										userId: payInfo.value.id,
										paymentId: payment.value.id,
										paymentStatus: '1',
										isVerified: '1',
										operate: new Date().toLocaleString() + '自动到账通过审核',
										operateEn: new Date().toLocaleString() + 'Automatically credited and approved through review',
										conferenceId: id.value,
										createdBy: '00000000-0000-0000-0000-000000000000',
										updatedBy: '00000000-0000-0000-0000-000000000000'
									});
									UserIsConference.value =4;
									uni.showToast({
										title:'支付成功',
										duration: 2000,
										success:function(){
											uni.navigateBack();
										}
									})
								}
								if(data.status ===  'TRADE_CLOSED' || data.status === 'WAIT_BUYER_PAY'){
									const uprs = await paymentUpdate({
										 ...payment.value,
										 tradeId:payment.value.tradeId,
										 paymentStatus:'0',
										 type: 'union',
									},payment.value.id);
								}
							},2000)
						}
						if(payResult.resultCode =='6001' && payResult.errMsg=="requestPayment:ok"){
							if(data.status === 'WAIT_BUYER_PAY'){
								paymentClose(id.value,miniOrder.merOrderId)
							}					
						}
					},
					fail:(err)=>{
						console.log(JSON.stringify(err))
						setTimeout(async function(){
						const { code, data } = await orderQuery(payment.value.tradeId,id.value)
						console.log(data);
							if(data.status === 'TRADE_SUCCESS'){
								const uprs = await paymentUpdate({
										 ...payment.value,
										 tradeId:payment.value.tradeId,
										 paymentStatus:'1',
										 paymentFee:payment.vlue.paymentFee,
										 type: 'union',
									},payment.value.id);
							}
							if(data.status ===  'TRADE_CLOSED' || data.status === 'WAIT_BUYER_PAY'){
								const uprs = await paymentUpdate({
									 ...payment.value,
									 tradeId:payment.value.tradeId,
									 paymentStatus:'0',
									 type: 'union',
								},payment.value.id);
							}
						},2000)
					}
				})
			}else{
				uni.showToast({
					title:data.message
				})
			}
		}else{
			console.log('aaa');
			const changeFee = data.paymentFee
			//弹出确认框 改变价格了
			uni.showModal({
				title:'缴费价格变为'+changeFee+'元',
				content:'是否继续缴费',
				success:(res)=> {
					if (res.confirm) {
						Paied(parseFloat(changeFee)*100 ,id.value,useUserInfo().getOpenid(),payInfo.value.id).then((result)=>{
							if(result.code == 0){
								uni.requestPayment({
									provider:'alipay',
									orderInfo:result.data.miniPayRequest.tradeNO,
									success:(payResult)=>{
										if(payResult.resultCode =='9000' && payResult.errMsg=="requestPayment:ok"){
											setTimeout( async function(){
												const { code, data } = await orderQuery(payment.value.tradeId,id.value)
												console.log(data);
												if(data.status === 'TRADE_SUCCESS'){
													const uprs = await paymentUpdate({
															 ...payment.value,
															 tradeId:payment.value.tradeId,
															 paymentStatus:'1',
															 paymentFee:changeFee,
															 type: 'union',
														},payment.value.id);
													const uplog = await paymentLog({
														userId: payInfo.value.id,
														paymentId: payment.value.id,
														paymentStatus: '1',
														isVerified: '1',
														operate: new Date().toLocaleString() + '自动到账通过审核',
														operateEn: new Date().toLocaleString() + 'Automatically credited and approved through review',
														conferenceId: id.value,
														createdBy: '00000000-0000-0000-0000-000000000000',
														updatedBy: '00000000-0000-0000-0000-000000000000'
													});
													UserIsConference.value =4;
													uni.showToast({
														title:'支付成功',
														duration: 2000,
														success:function(){
															uni.navigateBack();
														}
													})
												}
												if(data.status ===  'TRADE_CLOSED' || data.status === 'WAIT_BUYER_PAY'){
													const uprs = await paymentUpdate({
														 ...payment.value,
														 tradeId:payment.value.tradeId,
														 paymentStatus:'0',
														 type: 'union',
													},payment.value.id);
												}
											},2000)
										}
										if(payResult.resultCode =='6001' && payResult.errMsg=="requestPayment:ok"){
											paymentClose(id.value,result.data.merOrderId)
											setTimeout(function(){
												paymentUpdate({
													 ...payment.value,
													 tradeId:payment.value.tradeId,
													 paymentStatus:'0',
													 type: 'union',
												},payment.value.id);
											},1500)
										}
									},
									fail:(err)=>{
										paymentUpdate({
												 ...payment.value,
												 tradeId:payment.value.tradeId,
												 paymentStatus:'0',
												 type: 'union',
										},payment.value.id);
									}
								})
							}else{
								uni.showToast({
									title:result.data.message
								})
							}
						})
						
					} else if (res.cancel) {
						uni.showToast({
							title:'取消了缴费'
						})
						UserIsConference.value=0
					}
				}
			})
		}
	}
	
	onLoad(async (opt)=>{
		console.log(opt);
	    await $onLaunched;
		const cfcId = uni.getStorageSync('qrSinceId');
		console.log(cfcId);
		if(!!cfcId){
			id.value = cfcId
			uni.removeStorageSync('qrSinceId');
		}else{
			id.value = opt.id
		}
		getidentity(id.value).then((rlt)=>{
			identity.value = rlt.data.list
		})
		getstrategy(id.value).then((rlt)=>{
			strategy.value = rlt.data.list
		})
		getDetail();
	})
		
	
</script>

<style lang="scss" scoped>
	.tic{height:208rpx;}
	.tic image{width:100%;height:100%;}
	.bgblue{background-color: #005fea;}
	.w540{width:540rpx;}
	.bggray{background-color: #999; color:#666;}
	.bgred{background-color: #ef5757;}
</style>
